# 后序遍历
# 后序遍历是先遍历左子树，然后遍历右子树，最后访问树的根节点。


# 例子
"""
给定一个二叉树，返回它的 后序 遍历。

示例:

输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [3,2,1]

作者：力扣 (LeetCode)
链接：https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xebrb2/
来源：力扣（LeetCode）
著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
"""
from typing import List


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def postorderTraversal(self, root: TreeNode):
        r = []
        if root is not None:
            r.extend(self.postorderTraversal(root.left))
            r.extend(self.postorderTraversal(root.right))
            r.extend([root.val])
        return r

    def postorderTraversal2(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        stack = [root]
        t = type(root)
        res = []
        while stack:
            cur = stack.pop()
            if type(cur) != t and cur is not None:
                res.append(cur)
                continue
            if cur:
                stack.append(cur.val)
                stack.append(cur.right)
                stack.append(cur.left)
        return res


if __name__ == '__main__':
    tree = TreeNode(1)
    tree.right = TreeNode(2)
    tree.right.left = TreeNode(3)
    s = Solution()
    print(s.postorderTraversal(tree))